using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlServerCe;
using System.Drawing; 
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace FeedFly
{
    /// <summary>
    /// Form for adding new Feeds
    /// </summary>
    public partial class AddFeedForm : Form, FolderBrowseInterface
    {
        private int folderId;

        public AddFeedForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);            
        }

        public void PrepareForm(int folderId, string breadCrumbs)
        {
            string address = String.Empty;
            this.folderId = folderId;
            this.BreadCrumbLabel.Text = breadCrumbs;

            // TJ: check device clipboard for web address
            IDataObject clipObject = Clipboard.GetDataObject();
            if (clipObject.GetDataPresent(DataFormats.Text) &&
                Uri.IsWellFormedUriString(clipObject.GetData(DataFormats.Text).ToString(), UriKind.Absolute))
                    address = clipObject.GetData(DataFormats.Text).ToString();

            // RC: Check for address length
            if (address.Length > 1000)
            {
                feedAddressTextBox.Text = address.Substring(0, 1000);
                errorLabel.Text = "Copied URL exceeded 1000 characters.";
            }
            else
                feedAddressTextBox.Text = address;

            // TJ: Get item limit from db 
            this.itemLimitTrackBar.Maximum = Settings.MaxItemCount;
            this.itemLimitTrackBar.Value = Convert.ToInt16(Settings.DefaultItemLimit);
            this.ItemLimitLabel.Text = this.itemLimitTrackBar.Value.ToString();
        }

        private void addFeedMenuItem_Click(object sender, EventArgs e)
        {
            this.errorLabel.Text = String.Empty;

            if (feedAddressTextBox.Text.Length == 0)
            {
                this.errorLabel.Text = "Feed address is required.";
                return;
            }

            Uri feedUri;

            if (!Uri.TryCreate(feedAddressTextBox.Text, UriKind.Absolute, out feedUri))
            { 
                this.errorLabel.Text = "Not a valid web address.";
                return;
            }
            
            StringBuilder sql = new StringBuilder("SELECT 1 from Feed WHERE Address = '", 300);
            sql.Append(feedUri.ToString()).Append("'");

            // Check if address is in the db if is is not in db then save feed
            if (Data.ExecuteScalar(sql.ToString()) == null)
            {
                // TJ: moved this to save routine
                if (setDefaultLimitCheckBox.Checked == true)
                    Settings.DefaultItemLimit = itemLimitTrackBar.Value.ToString();

                // TJ: Updated to use download queue and attempt to download
                FeedBase newFeedData = new FeedBase();
                newFeedData.Address = feedUri.AbsoluteUri;
                newFeedData.FolderId = this.folderId;
                newFeedData.ItemLimit = (short)itemLimitTrackBar.Value;
                
                Net.EnqueueDownload(new FeedUnknown(newFeedData));  
              
                ThreadPool.QueueUserWorkItem(new WaitCallback(Net.ProcessDownloads));

                Screens.Main.Show();
                Hide();
            }
            else
                this.errorLabel.Text = "Feed address already exists.";

        }

        private void cancelMenuItem_Click(object sender, EventArgs e)
        {
            //  Will clear the error box if any before leaving this window
            errorLabel.Text = String.Empty;
            Screens.Main.Show();
            Hide();
        }

        public void FolderChosen(int folderId, string folderName, string breadCrumbs)
        {
            if (this.folderId != folderId)
            {
                this.folderId = folderId;
                this.BreadCrumbLabel.Text = breadCrumbs;
            }
        }

        private void ChangeParent(object sender, EventArgs e)
        {
            Screens.SelectFolder.PrepareForm(this);
            Screens.SelectFolder.Show();
            Hide();
        }

        private void TEFeedAddress_TextChanged(object sender, EventArgs e)
        {
            errorLabel.Text = String.Empty;
        }

        private void errorLabel_TextChanged(object sender, EventArgs e)
        {
            errorLabel.Visible = (errorLabel.Text.Length > 0);                 
        }

        private void itemLimitTrackBar_ValueChanged(object sender, EventArgs e)
        {
            ItemLimitLabel.Text = itemLimitTrackBar.Value.ToString();
        }

        private void CopyMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(feedAddressTextBox.SelectedText);
        }

        private void PasteMenuItem_Click(object sender, EventArgs e)
        {
            IDataObject clipObject = Clipboard.GetDataObject();
            if (clipObject.GetDataPresent(DataFormats.Text))
                ((TextBox)sender).Text = clipObject.GetData(DataFormats.Text).ToString();                
        }
    }
}